<template>
  <div class="album">
    <h1 class="title">企业相册</h1>
    <div class="box">
      <div class="wrapper">
        <div class="top">
          <el-button type="primary" size="medium" @click="toUpload"><svg-icon icon-class="upload-img" /> 上传照片</el-button>
          <el-button size="medium" @click="edit('new')">创建相册</el-button>
          <span>您的企业相册总容量为500张，已使用{{ totalPicsCount }}张</span>
        </div>
        <div v-if="albumList.length === 0" class="none">
          <p class="img"><img src="../../../assets/images/none-album.png" alt="暂无相册"></p>
          <h4>暂无图片</h4>
          <p>您还没有上传图片哦～</p>
        </div>
        <ul v-else class="list">
          <li v-for="album in albumList" :key="album.id">
            <div class="img-box" @click="toDetail(album)">
              <el-image style="width: 200px; height: 200px" :src="qnPath(album.image)" fit="fit" />
            </div>
            <div class="info">
              <p @click="toDetail(album)"><span class="text-ellipsis">{{ album.name }}</span>({{ album.albumDetails.length }}张)</p>
              <div>
                <el-button type="text" @click="edit('edit', album)">编辑</el-button>
                <el-button type="text" class="del" @click="delAlbum(album.id)">删除</el-button>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <!-- dialog -->
    <el-dialog v-el-drag-dialog class="dialog-photo" width="900px" :visible.sync="dialogvisible">
      <h3 slot="title">{{ dialogTitle }}</h3>
      <div class="dialog-body">
        <el-form ref="dialogForm" :model="dialogForm" label-width="100px">
          <el-form-item v-if="dialogTitle === '上传照片'" class="name-ipt" prop="name" label="上传到：">
            <el-select v-model="uploadTarget" placeholder="请选择相册" @change="switchUploadTarget">
              <el-option
                v-for="item in albumList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-else class="name-ipt" prop="name" label="相册名称：" :rules="[{ required: true, message: '请输入相册名称', trigger: 'blur' }]">
            <el-input v-model.trim="dialogForm.name" size="medium" placeholder="请输入相册名称" clearable />
          </el-form-item>
          <el-form-item prop="name" label="上传照片：">
            <div class="pic-box">
              <div v-for="(pic, i) in dialogFormPhotosBak" :key="pic.id" class="pic">
                <div class="img">
                  <el-image style="width: 120px; height: 95px" :src="qnPath(pic.image)" fit="fill" :preview-src-list="previewPics" lazy>
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline" />
                    </div>
                  </el-image>
                  <p class="img-del" @click="delPic(pic, i)"><i class="el-icon-delete" /></p>
                </div>

                <el-input v-model.trim="pic.name" size="mini" clearable />
              </div>
              <image-upload :size="4096" imgname="相册图片" :multiple="true" @onSuccess="picUploadSuc">
                <p><i class="el-icon-plus" /><span>添加照片</span></p>
              </image-upload>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="btns">
        <el-button size="medium" type="primary" @click="dialogOK">确 定</el-button>
        <el-button size="medium" @click="goBack">返 回</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import ImageUpload from '@/components/ImagesUpload';
import { mapGetters } from 'vuex';
import { createAlbum, updateAlbum, deleteAlbum, deletePic, getAlbumList } from '@/api/shop';
// import { deleteQnImg } from '@/api/qiniu';
export default {
  name: 'Album',
  components: {
    ImageUpload
  },
  data() {
    return {
      totalPicsCount: 0,
      dialogTitle: '创建相册',
      dialogvisible: false,
      albumList: [],
      albumListSumarry: [], // 将要传给详情页的相册列表
      previewPics: [],
      dialogForm: {
        name: '',
        albumDetails: []
      },
      dialogFormPhotosBak: [],
      deletePicsBak: [],
      addPicsBak: [], // 暂存上传的图片
      uploadTarget: '' // 图片上传相册ID
    };
  },
  computed: {
    ...mapGetters(['qiniuResUrl', 'shopInfo'])
  },
  watch: {
    dialogFormPhotosBak(newPic) {
      if (newPic) {
        newPic.forEach(pic => {
          this.previewPics.push(this.qnPath(pic.image));
        });
      }
    }
  },
  created() {
    this.getAlbumList();
  },
  activated() {
    this.getAlbumList();
  },
  methods: {
    toDetail(album) {
      this.$router.push({ name: 'AlbumDetail', params: { id: album.id }, query: { list: JSON.stringify(this.albumListSumarry) }});
    },
    switchUploadTarget(val) {
      this.dialogFormPhotosBak = [];
      const selectedAlbum = this.albumList.filter(album => {
        return album.id === val;
      });
      this.dialogForm = selectedAlbum[0];
      selectedAlbum[0].albumDetails.map(pic => {
        this.dialogFormPhotosBak.push(pic);
      });
    },
    toUpload() {
      if (this.albumList.length > 0) {
        this.edit('upload');
      } else {
        this.edit('new');
      }
    },
    deletePic() {
      const arr = [];
      this.deletePicsBak.map(pic => {
        arr.push(pic.id);
      });
      new Promise((resolve, reject) => {
        deletePic({ id: arr.join(',') }).then(({ data }) => {
          resolve(data);
        }).catch(err => {
          reject(err);
        });
      });
    },
    getAlbumList() {
      this.totalPicsCount = 0;
      this.albumListSumarry = [];
      new Promise((resolve, reject) => {
        getAlbumList({ shopId: this.shopInfo.id }).then(({ data }) => {
          this.albumList = data.size;
          this.albumList.map(album => {
            this.albumListSumarry.push({ id: album.id, name: album.name, image: album.image });
            this.totalPicsCount += album.albumDetails.length;
          });
          resolve(data);
        }).catch(err => {
          reject(err);
        });
      });
    },
    edit(type, album = {}) {
      this.dialogFormPhotosBak = [];
      this.addPicsBak = [];
      this.dialogForm = {
        name: '',
        albumDetails: []
      };
      if (type === 'new') {
        this.dialogTitle = '创建相册';
      } else if (type === 'upload') {
        this.dialogTitle = '上传照片';
      } else {
        const copyedAlbum = JSON.parse(JSON.stringify(album));
        this.dialogTitle = '编辑相册';
        this.dialogForm = copyedAlbum;
        copyedAlbum.albumDetails.map(pic => {
          this.dialogFormPhotosBak.push(pic);
        });
      }
      this.dialogvisible = true;
    },
    delAlbum(id) {
      this.$confirm('此操作将永久删除该相册, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        new Promise((resolve, reject) => {
          deleteAlbum({ id }).then(({ data }) => {
            this.$message({
              type: 'success',
              message: '删除相册成功!',
              duration: 1500,
              onClose: () => {
                this.getAlbumList();
              }
            });
            resolve(data);
          }).catch(err => {
            reject(err);
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    goBack() {
      this.dialogvisible = false;
      this.dialogForm = {};
      this.dialogFormPhotosBak = [];
      this.deletePicsBak = [];
      this.getAlbumList();
    },
    dialogOK() {
      this.dialogForm.albumDetails = this.dialogFormPhotosBak;
      const { name, albumDetails } = this.dialogForm;
      const shopId = this.shopInfo.id;
      if (!name) {
        this.$message({
          type: 'warning',
          message: '请输入相册名'
        });
        return;
      }
      if (this.dialogTitle === '创建相册') {
        if (albumDetails.length === 0) {
          this.$message({
            type: 'warning',
            message: '请至少上传一张图片'
          });
          return;
        }
        new Promise((resolve, reject) => {
          createAlbum({ name, shopId, albumDetails }).then(({ data }) => {
            this.$message({
              type: 'success',
              message: '创建相册成功！',
              duration: 1500,
              onClose: () => {
                this.deletePic();
                this.goBack();
              }
            });
            resolve(data);
          }).catch(err => {
            reject(err);
          });
        });
      } else {
        new Promise((resolve, reject) => {
          updateAlbum({ id: this.dialogForm.id, name, shopId, albumDetails }).then(({ data }) => {
            this.$message({
              type: 'success',
              message: '编辑相册成功！',
              duration: 1500,
              onClose: () => {
                this.deletePic();
                this.goBack();
              }
            });
            resolve(data);
          }).catch(err => {
            reject(err);
          });
        });
      }
    },
    picUploadSuc(res) {
      const picNameArr = res.replace(this.qiniuResUrl, '').split('-');
      picNameArr.shift();
      const picName = picNameArr.join('');
      this.dialogForm.id ? this.dialogFormPhotosBak.push({ name: picName, image: res, shopId: this.shopInfo.id, albumId: this.dialogForm.id, id: '' }) : this.dialogFormPhotosBak.push({ name: picName, image: res, shopId: this.shopInfo.id });
      this.addPicsBak.push(res);
    },
    delPic(pic, index) { // 只是暂时将页面上的图片删除，不显示
      this.dialogFormPhotosBak.splice(index, 1);
      this.deletePicsBak.push(pic);
    }
  }
};
</script>
<style lang="scss" scoped>
.album{
	background-color: #fff;
	width: 100%;
	border-radius: 2px;
	font-size: $fontSizeBase;
	color: $textColorBase;
	line-height: calc(22/ 14);
	.box{
		padding-top: 50px;
		min-height: calc(100vh - 255px);
		display: flex;
		align-items: flex-start;
		justify-content: center;
	}
  .none{
    width: 100%;
		min-height: calc(100vh - 255px - 85px);
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    h4{
      font-size: 18px;
      font-weight: bolder;
      color: #3C4353;
      margin: 10px 0 ;
    }
  }
	.wrapper{
		display: flex;
		align-items: flex-start;
		flex-direction: column;
		width: 80%;
		max-width: 1170px;
	}
	.top{
		span{
			margin-left: 15px;
		}
	}
	.list{
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
		flex-wrap: wrap;
		margin-top: 30px;
		li{
			max-width: 240px;
			margin-bottom: 25px;
      margin-right: 25px;
		}
	}
	.img-box{
		width: 210px;
		height: 210px;
		display: flex;
		align-items: center;
		justify-content: center;
		border: 1px solid $borderColor;
    cursor: pointer;
	}
	.info{
		display: flex;
		align-items: center;
		justify-content: space-between;
		max-width: 210px;
		&>p{
			flex: 0 0 60%;
			max-width: 60%;
			display: flex;
			align-items: center;
      cursor: pointer;
			span{
				width: 60%;
			}
		}
		.del{
			color: $textColorDark;
		}
	}
}

.dialog-photo{
	.h3{
		color: $textColorDark;
	}
	/deep/ .el-dialog__body,/deep/ .el-dialog__footer{
		padding-right: 50px;
	}
	/deep/ .el-dialog__body{
		border-top: 1px solid $borderColor;
		padding-bottom: 10px;
	}
	/deep/ .el-dialog__footer{
		padding-top: 0;
	}
	.name-ipt{
		max-width: 45%;
	}
	.pic-box{
		height: 285px;
		display: flex;
		align-items: flex-start;
		flex-wrap: wrap;
		overflow-y: scroll;
		padding: 12px;
		border: 1px solid $borderColor;
	}
	.pic,.upload{
		width: 120px;
		flex: 0 0 120px;
		margin-right: 20px;
	}
	.pic{
		display: flex;
		flex-direction: column;
		margin-bottom: 20px;
		&:nth-child(5n){
			margin-right: 0;
		}
		/deep/ .el-input{
			line-height: 25px;
		}
		/deep/ .el-input__inner{
			height: 25px;
      line-height: 25px;
			padding: 0 10px;
			border-radius: 2px;
		}
	}
	.img{
		position: relative;
		height: 95px;
		&:hover .img-del{
			display: block;
		}
	}
	.img-del{
		display: none;
		width: 100%;
		height: 24px;
		line-height: 24px;
		text-align: center;
		background-color: rgba(0,0,0, 0.3);
		position: absolute;
		bottom: 0;
		left: 0;
		transition: all 0.2s ease;
		cursor: pointer;
		.el-icon-delete{
			color: #fff;
		}
	}
	.upload{
		height: 120px;
		background-color: #F9FBFC;
		border: 1px solid $borderColor;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		margin-right: 0;
		.el-icon-plus,span{
			display: block;
			text-align: center;
		}
		.el-icon-plus{
			font-size: 24px;
			color: $mainColor;
		}
		span{
			font-size: 12px;
			color: #A8ABB8;
		}
	}
	.btns{
		text-align: left;
		padding-left: 100px;
	}
}
</style>
